package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.LeaseEquipmentAdapter;
import com.isunland.managesystem.base.Base;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.entity.DataStatus;
import com.isunland.managesystem.entity.LeaseSubList;
import com.isunland.managesystem.entity.LeaseSubListOriginal;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * 对象功能: 租赁设备列表
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: wangyanan
 * 创建时间: 2017-02-16 13:48:00
 */

public class LeaseEquipmentListFragment extends BaseListFragment {
  public static final String EXTRA_MAINID =
      LeaseEquipmentListFragment.class.getSimpleName() + ".EXTRA_MAINID";
  public static final String EXTRA_STATUS =
      LeaseEquipmentListFragment.class.getSimpleName() + ".EXTRA_STATUS";
  public static final String EXTRA_DEPOSIT =
      LeaseEquipmentListFragment.class.getSimpleName() + ".EXTRA_DEPOSIT";
  public static final String EXTRA_LEASEMONEY =
      LeaseEquipmentListFragment.class.getSimpleName() + ".EXTRA_LEASEMONEY";
  public static final String EXTRA_IS_UPDATE =
      LeaseEquipmentListFragment.class.getSimpleName() + ".EXTRA_IS_UPDATE";
  private static final int REQUEST_ADD = 3;
  private static final int REQUEST_DETAIL = 4;
  private ArrayList<LeaseSubList> mList;
  private LeaseEquipmentAdapter<LeaseSubList> mAdapter;
  private String mainId;
  private String status;
  private boolean mIsUpdate;//是否是更新操作.
  private Intent mIntentExtra;//回传钱数的intent.

  public static LeaseEquipmentListFragment newInstance(String mainId, String status,
      boolean isUpdate) {
    LeaseEquipmentListFragment fragment = new LeaseEquipmentListFragment();
    Bundle args = new Bundle();
    args.putString(EXTRA_MAINID, mainId);
    args.putString(EXTRA_STATUS, status);
    args.putBoolean(EXTRA_IS_UPDATE, isUpdate);
    fragment.setArguments(args);
    return fragment;
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
    BaseVolleyActivity mActivity = (BaseVolleyActivity) getActivity();
    ActionBar actionBar = mActivity.getSupportActionBar();

    if (actionBar != null) {
      actionBar.setTitle(R.string.leaseEquipmentManagement);
      actionBar.setDisplayHomeAsUpEnabled(true);
    }
    mList = new ArrayList<>();
    mainId = getArguments().getString(EXTRA_MAINID);
    status = getArguments().getString(EXTRA_STATUS);
    mIsUpdate = getArguments().getBoolean(EXTRA_IS_UPDATE);
    mAdapter = new LeaseEquipmentAdapter<>(mActivity, mList);
  }

  @Override public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    int padding = MyUtils.dip2px(getActivity().getApplicationContext(), 16);
    //noinspection deprecation
    mListview.setDivider(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
    mListview.setDividerHeight(padding);
    mListview.setPadding(0, 0, 0, padding);

    setListAdapter(mAdapter);
  }

  @Override public String getUrl() {
    return ApiConst.URL_LEASE_EQUIPMENT_LIST;
    //return ApiConst.URL_LATEST_VERSION;
  }

  @Override public HashMap<String, String> getparameters() {
    HashMap<String, String> params = new HashMap<>();
    params.put("mainId", mainId);
    return params;
  }

  @Override public void resolveResponse(String json) {
    //json = MyUtils.readAssetsFile(mActivity, "testAppointmentOrder.json");
    LeaseSubListOriginal result = new Gson().fromJson(json, LeaseSubListOriginal.class);

    if (result.getResult() == Base.SUCCESS && result.getRows() != null) {
      //if (result.getRows() != null) {
      //获取列表成功
      //LogUtil.i("date="+result.getRows().get(0).getRegDate());
      mList.clear();
      mList.addAll(result.getRows());
      mAdapter.notifyDataSetChanged();
      //更新操作时,需要计算预付款合计和租赁费用合计
      if (mIsUpdate) {
        calculateMoney(result.getRows());
      }
    } else {
      ToastUtil.show("获取列表失败");
    }
  }

  /**
   * 计算预付款合计和租赁费用合计.
   *
   * @param rows 接口获取的设备列表
   */
  private void calculateMoney(ArrayList<LeaseSubList> rows) {
    if (rows == null || rows.size() == 0) return;
    double leaseTotal = 0;
    double depositTotal = 0;
    for (LeaseSubList item : rows) {
      leaseTotal += MyUtils.valueOfDouble(item.getLeaseCostTotal(), 0);
      depositTotal += MyUtils.valueOfDouble(item.getDepositCostTotal(), 0);
    }
    if (mIntentExtra == null) {
      mIntentExtra = new Intent();
    }
    mIntentExtra.putExtra(EXTRA_DEPOSIT, String.valueOf(depositTotal));
    mIntentExtra.putExtra(EXTRA_LEASEMONEY, String.valueOf(leaseTotal));
    mActivity.setResult(Activity.RESULT_OK, mIntentExtra);
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) return;

    if (requestCode == REQUEST_ADD) {

      volleyPost();
      return;
    }
    if (requestCode == REQUEST_DETAIL) {

      volleyPost();
      return;
    }
    super.onActivityResult(requestCode, resultCode, data);
  }

  @Override public void onListItemClick(ListView l, View v, int position, long id) {
    LeaseSubList item = mAdapter.getItem(position - mListview.getHeaderViewsCount());
    LeaseEquipmentDetailActivity.newInstance(this, mActivity, item, status, REQUEST_DETAIL);
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    if (!mIsUpdate) return;//不是更新时只是查看,没有菜单.
    if (status == null) return;

    if (status.equals(DataStatus.NEW) || status.equals(DataStatus.NEWBACK) || status.equals(
        DataStatus.ORDER_CANCEL) || status.equals(DataStatus.BACK_ORDER_PUBLISH)) {
      inflater.inflate(R.menu.menu_add, menu);
    }

    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        getActivity().finish();
        break;
      case R.id.menu_item_add:
        LeaseEquipmentUpdateActivity.startActivityForResult(this, mActivity, null, mainId,
            REQUEST_ADD);
        break;
      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  //@Override
  //public void click(View v) {
  //    if (v == null) return;
  //    switch (v.getId()) {
  //        case R.id.tv_cancel://取消
  //            if (v.getTag() instanceof Integer) {
  //                int position = (Integer) v.getTag();
  //                LeaseMainList item = mAdapter.getItem(position);
  //                ToastUtil.show("取消" + item.getId());
  //            }
  //            return;
  //        case R.id.tv_reminder://催单
  //            if (v.getTag() instanceof Integer) {
  //                int position = (Integer) v.getTag();
  //                LeaseMainList item = mAdapter.getItem(position);
  //                ToastUtil.show("催单" + item.getId());
  //            }
  //            return;
  //        default:
  //            break;
  //    }
  //}
}
